package com.guapi.schedule.taskCenter;

import cn.hutool.core.collection.CollectionUtil;
import com.guapi.dao.IpRecord;
import com.guapi.service.IpRecordService;
import com.guapi.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class IpRecordSchedule {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private IpRecordService ipRecordService;

    /**
     * 定时记录redis服务器中的IP记录缓存(每10分钟)并清除
     */
    public void writeIpRecord() {
        String inWebIps = RedisUtil.getInWebIps();
        ArrayList<String> ips = new ArrayList<>();
        HashMap<String, Long> ipTimeRecords = (HashMap<String, Long>) redisTemplate.opsForValue().get(inWebIps);
        if (CollectionUtil.isEmpty(ipTimeRecords)) {
            return;
        }
        for (String ip : ipTimeRecords.keySet()) {
            String inWebIp = RedisUtil.getInWebIp(ip);
            IpRecord ipRecord = new IpRecord();
            ipRecord.setIp(ip);
            ipRecord.setInTime(ipTimeRecords.get(ip));
            Map ipMap = (Map<String, List<IpRecord>>) redisTemplate.opsForValue().get(inWebIp);
            List record = (List) ipMap.get(inWebIp);
            // TODO: 2023/5/13 判空
            ipRecord.setCount(record.size());
            ipRecordService.save(ipRecord);
            ips.add(inWebIp);
        }
        redisTemplate.delete(inWebIps);
        redisTemplate.delete(ips);
    }
}
